<template>
  <div class="recommend-view">
    <!-- 1. 轮播图（适配接口 + 图片容错） -->
    <el-carousel height="200px" :autoplay="true" indicator-position="outside">
      <template v-if="bannerLoading">
        <el-skeleton active height="200px" style="width: 100%" />
      </template>
      <!-- 轮播图项：用 ElImage 替代 img，处理加载失败 -->
      <el-carousel-item v-for="banner in bannerList" :key="banner.id">
        <el-image
            :src="banner.bannerUrl"
            class="banner-img"
            :alt="'轮播图' + (banner.id + 1)"
            :error-src="'/src/assets/images/banner-error.png' || 'https://picsum.photos/1200/200?random=error'"        fit="cover"
        />
      </el-carousel-item>
    </el-carousel>

    <!-- 2. 推荐歌单 -->
    <div class="recommend-section" style="margin-top: 30px;">
      <div class="section-header">
        <h3>推荐歌单</h3>
        <el-button size="small" @click="loadRecommendedPlaylists" icon="Refresh">
          刷新推荐
        </el-button>
      </div>



      <!-- 歌单详情弹窗 -->
      <el-dialog
          title="歌单详情"
          v-model="dialogVisible"
          width="80%"
          :before-close="handleClose"
          :fullscreen="isMobile"
      >
        <div v-if="detailLoading" class="detail-loading">
          <el-skeleton :rows="6" />
        </div>
        <div v-else>
          <!-- 歌单头部信息 -->
          <div class="detail-header">
            <img
                :src="playlistDetail.coverUrl || 'https://picsum.photos/300/300?random=' + playlistDetail.playlistId"
                class="detail-cover"
                alt="歌单封面"
            />
            <div class="detail-info">
              <h3>{{ playlistDetail.title }}</h3>
              <p>风格：{{ playlistDetail.style || '未知风格' }}</p>
              <p>简介：{{ playlistDetail.introduction || '暂无简介' }}</p>
              <div class="detail-actions">
                <!-- 未登录状态 -->
                <el-button
                    v-if="!isLogin()"
                    type="primary"
                    @click="showLogin"
                >
                  登录后收藏
                </el-button>
                <!-- 已登录状态：严格根据后端返回的likeStatus判断 -->
                <el-button
                    v-else
                    type="primary"
                    :icon="playlistDetail.likeStatus === 1 ? 'HeartFilled' : 'Heart'"
                    @click="toggleLikeStatus"
                    :loading="toggleLikeLoading"
                >
                  {{ playlistDetail.likeStatus === 1 ? '取消收藏' : '收藏' }}
                </el-button>
              </div>
            </div>
          </div>

          <!-- 歌曲列表 -->
          <div class="detail-songs">
            <h4>歌曲列表 ({{ playlistDetail.songs?.length || 0 }})</h4>
            <el-table :data="playlistDetail.songs || []" border style="width: 100%">
              <el-table-column label="序号" type="index" width="60" />
              <el-table-column label="封面">
                <template #default="scope">
                  <img
                      :src="scope.row.coverUrl || 'https://picsum.photos/60/60?random=' + scope.row.songId"
                      class="song-cover"
                      alt="歌曲封面"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="name" label="歌曲名称" />
              <el-table-column prop="artistName" label="歌手" />
              <el-table-column prop="album" label="专辑" />
              <el-table-column label="操作">
                <template #default="scope">
                  <!-- 播放按钮 -->
                  <el-button icon="Play" size="small" @click.stop="playSong(scope.row)" > <el-icon>
                    <VideoPlay/>
                  </el-icon>
                    播放
                  </el-button>

                  <!-- 歌曲收藏：根据登录状态显示不同内容 -->
                  <el-button
                      v-if="isLogin()"
                      size="small"
                      @click.stop="likeSong(scope.row)"
                      :type="scope.row.likeStatus === 1 ? 'danger' : 'default'"
                      :loading="scope.row.likeLoading"
                  > <el-icon>
                    <Star/>
                  </el-icon>
                    {{ scope.row.likeStatus === 1 ? '取消收藏' : '收藏' }}
                  </el-button>

                  <!-- 未登录状态：显示"收藏请先登录" -->
                  <el-button
                      v-else
                      size="small"
                      @click.stop="showLogin"
                      class="login-prompt-btn"
                  ><el-icon>
                    <Star/>
                  </el-icon>
                    请先登录
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 评论区 -->
          <div class="detail-comments">
            <h4>评论列表 ({{ playlistDetail.comments?.length || 0 }})</h4>
            <div v-if="playlistDetail.comments?.length === 0" class="no-comment">
              暂无评论，快来发表第一条评论吧
            </div>
            <div v-else class="comments-list">
              <el-card
                  v-for="comment in playlistDetail.comments"
                  :key="comment.commentId"
                  class="comment-card"
                  :body-style="{ padding: '10px' }"
              >
                <div class="comment-item">
                  <img
                      :src="comment.userAvatar || 'https://picsum.photos/40/40?random=' + comment.commentId"
                      class="comment-avatar"
                      alt="用户头像"
                  />
                  <div class="comment-info">
                    <div class="comment-header">
                      <div class="comment-username">{{ comment.username }}</div>
                      <div class="comment-time">{{ comment.createTime }}</div>
                    </div>
                    <div class="comment-content">{{ comment.content }}</div>
                    <div class="comment-actions">
                      <!-- 点赞评论 -->
                      <el-button
                          icon="Thumb"
                          size="small"
                          @click.stop="isLogin() ? toggleCommentLike(comment) : showLogin()"
                          :loading="comment.likeLoading"
                          :type="comment.isLiked ? 'primary' : 'default'"
                      >
                        {{ comment.likeCount || 0 }}
                      </el-button>

                      <!-- 删除评论：仅评论作者可见 -->
                      <el-button
                          v-if="currentUser && currentUser.userId && comment.userId && String(currentUser.userId) === String(comment.userId)"
                          icon="Delete"
                          size="small"
                          type="danger"
                          @click.stop="deleteComment(comment)"
                          :loading="comment.deleteLoading"
                      >
                        删除
                      </el-button>
                    </div>
                  </div>
                </div>
              </el-card>
            </div>

            <!-- 发表评论区域 -->
            <div v-if="isLogin()" class="add-comment">
              <el-input
                  v-model="commentContent"
                  type="textarea"
                  placeholder="请输入评论内容"
                  :rows="3"
                  style="margin-top: 10px;"
              />
              <el-button type="primary" @click="sendComment" :loading="sendCommentLoading" style="margin-top: 10px;">发表评论</el-button>
            </div>
            <div v-else class="need-login-comment">
              <el-alert title="请登录后发表评论" type="info" show-icon />
              <el-button type="text" @click="showLogin" style="margin-top: 10px;">去登录</el-button>
            </div>
          </div>
        </div>
        <template #footer>
          <el-button @click="dialogVisible = false">关闭</el-button>
        </template>
      </el-dialog>

      <div class="card-list" v-if="!playlistLoading">
        <el-card
            v-for="(playlist, idx) in recommendedPlaylists"
            :key="idx"
            class="recommend-card"
            :body-style="{ padding: '10px' }"
            @click="getPlaylistDetail(playlist.id || playlist.playlistId)"
            :disabled="!playlist.id && !playlist.playlistId"
        >
          <el-image
              :src="playlist.coverUrl || `https://picsum.photos/120/120?random=${idx}`"
              class="card-cover"
              :alt="playlist.title"
              :error-src="`https://picsum.photos/120/120?random=cover${idx}`"
              fit="cover"
          />
          <div class="card-label">{{ playlist.title || '未知歌单' }}</div>
        </el-card>
        <div class="empty-tip" v-if="recommendedPlaylists.length === 0">
          暂无推荐歌单，点击刷新试试~
        </div>
      </div>
      <el-skeleton active v-else class="playlist-skeleton" :count="10" />
    </div>

    <!-- 3. 推荐歌曲（对接 SongController 接口） -->
    <div class="recommend-section">
      <div class="section-header-actions">
        <h3>推荐歌曲</h3>
        <el-tag type="info" @click="loadRecommendedSongs">刷新推荐</el-tag>
        <el-button
            size="small"
            type="text"
            @click="goToAllSongs"
            v-if="recommendedSongs.length > 0"
        >
          查看全部歌曲 →
        </el-button>
      </div>

      <div v-if="!songLoading">
        <el-table :data="recommendedSongs" border style="width: 100%; margin-top: 10px;">
          <el-table-column label="标题" width="300">
            <template #default="scope">
              <div class="song-title">
                <el-image
                    v-if="scope.row.coverUrl"
                    :src="scope.row.coverUrl"
                    class="song-cover-sm"
                    :alt="scope.row.songName"
                    :error-src="`https://picsum.photos/30/30?random=song${scope.row.songId}`"
                    fit="cover"
                />
                <span>{{ scope.row.songName || '未知歌曲' }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="artistName" label="歌手" width="200" />
          <el-table-column prop="album" label="专辑" width="200" />
          <el-table-column label="时长" width="100">
            <template #default="scope">
              {{ formatTime(scope.row.duration) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="240">
            <template #default="scope">
              <el-button
                  size="small"
                  @click="playSong(scope.row)"
                  :disabled="!scope.row.songId"
              >
                播放
              </el-button>
              <el-button
                  @click="likeSong(scope.row)"
                  :type="scope.row.likeStatus === 1 ? 'danger' : 'default'"
                  :loading="scope.row.likeLoading"
                  circle
                  class="like-btn"
              >
                <el-icon>
                  <Star/>
                </el-icon>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="empty-tip" v-if="recommendedSongs.length === 0">
          暂无推荐歌曲，点击刷新试试~
        </div>
      </div>
      <el-skeleton active v-else style="width: 100%" :rows="8" />
    </div>
  </div>
</template>

<script setup>
// 1. 基础依赖导入
import http from "@/request/http.js";
import { ref, onMounted, watch } from 'vue'
import {
  ElMessage,
  ElSkeleton,
  ElButton,
  ElCard,
  ElTable,
  ElTableColumn,
  ElImage,
  ElTag,
  ElAlert,
  ElDialog, ElInput
} from 'element-plus'
import axios from 'axios'
import { useRouter } from 'vue-router'

// 2. API 统一导入（对应 api 目录封装）
import bannerApi from '../api/banner.js'
import playlistApi from '../api/playlist.js'
import songApi from '../api/song.js'
import favoriteApi from '../api/favorite.js'

// 3. 工具函数导入
import { isLogin, getToken } from '../utils/auth'
import { formatTime, formatNumber } from '../utils/format.js'
import {Star, VideoPlay} from "@element-plus/icons-vue";
import {usePlayer} from "@/utils/player.js";

// 4. 路由实例
const router = useRouter()

// -------------------------- 基础配置 --------------------------

axios.defaults.headers.post['Content-Type'] = 'application/json'

// -------------------------- 类型定义（增强健壮性） --------------------------
/**
 * 轮播图数据类型（适配接口返回的 items 子项）
 * @typedef {Object} BannerItem
 * @property {number} id - 轮播图ID
 * @property {string} bannerUrl - 轮播图图片地址
 * @property {string} bannerStatus - 状态（ENABLE=启用，其他=禁用）
 */

/**
 * 歌曲数据类型（前端处理后）
 * @typedef {Object} SongItem
 * @property {number} songId - 歌曲ID
 * @property {string} songName - 歌曲名
 * @property {string} artistName - 歌手名
 * @property {string} album - 专辑名
 * @property {string} [coverUrl] - 歌曲封面
 * @property {number} duration - 时长（秒）
 * @property {boolean} isLiked - 是否已收藏
 */

// -------------------------- 1. 轮播图相关（核心适配接口） --------------------------
/** @type {BannerItem[]} 轮播图列表（仅存启用状态） */
const bannerList = ref([])
const bannerLoading = ref(true)

/**
 * 加载轮播图（适配接口：res.data.data.items + 过滤ENABLE状态 + 缓存优化）
 */
const loadBanner = async () => {
  bannerLoading.value = true
  try {
    const res = await bannerApi.getActiveBannerList('ALL')
    console.log('轮播图接口响应：', res) // 应输出 {code:0, message:"操作成功", data:{total:10, items:[...]}}

    // 因为 request.js 已确保 res.code === 0 才返回，所以可简化判断
    const bannerData = res.data // 后端 data 字段（含 total 和 items）
    const rawBannerList = bannerData?.items || []

    const validBanners = rawBannerList.filter(banner =>
        banner.bannerStatus === 'ENABLE' && banner.bannerUrl
    )

    if (validBanners.length === 0) {
      ElMessage.warning('暂无可用轮播图')
      bannerList.value = []
      return
    }

    bannerList.value = validBanners
    sessionStorage.setItem('validBanners', JSON.stringify(validBanners))
    ElMessage.success(`轮播图加载成功：${validBanners.length}张`)

  } catch (err) {
    console.error('轮播图加载失败：', err)
    ElMessage.error('轮播图加载失败，请重试')
    bannerList.value = []
  } finally {
    bannerLoading.value = false
  }
}
// -------------------------- 2. 推荐歌单相关 --------------------------
const recommendedPlaylists = ref([])
const playlistLoading = ref(false)

// 登录相关状态
const currentUser = ref({})

// 操作加载状态（避免重复点击）
const toggleLikeLoading = ref(false) // 歌单收藏/取消加载
const sendCommentLoading = ref(false) // 发表评论加载
// 歌单详情相关状态（与后端字段对齐）
const dialogVisible = ref(false)
const detailLoading = ref(false)
const playlistDetail = ref({
  playlistId: '', // 后端返回的歌单ID
  title: '',
  coverUrl: '',
  introduction: '',
  style: '',
  songs: [], // 歌曲列表，每个song含likeStatus
  comments: [], // 评论列表
  likeStatus: 0 // 歌单收藏状态：0=未收藏，1=已收藏
})
const commentContent = ref('')

// 窗口大小变化处理
const handleResize = () => {
  isMobile.value = window.innerWidth < 768
}
const isMobile = ref(window.innerWidth < 768)

// 登录状态变化处理
const handleLoginStatusChange = () => {
  initUserState()
  if (activeTab.value === 'favorite') {
    fetchFavoritePlaylists()
  }
  // 登录状态变化后，刷新当前歌单详情的收藏状态
  if (dialogVisible.value) {
    getPlaylistDetail(playlistDetail.value.playlistId)
  }
}

const initUserState = async () => {
  try {
    // 1. 先获取本地存储的Token（无Token则无需请求接口，直接设为空）
    const token = getToken();
    if (!token) {
      currentUser.value = {}; // 未登录：空对象
      console.log("初始化用户状态：未检测到Token，用户未登录");
      return;
    }

    // 2. 携带Token请求后端接口（后端通过Token识别当前用户）
    const response = await http.get('/user/getUserInfo', {
      headers: {
        // 后端需通过Authorization头获取Token，格式为 Bearer + 空格 + Token
        'Authorization': `Bearer ${token}`
      }
    });

    // 3. 处理后端返回结果（需根据后端实际返回结构调整，这里假设后端返回DataVo<UserVO>）
    // 假设后端返回格式：{ code: 0, data: UserVO, message: "success" }（DataVo结构）
    if (response.code === 0 && response.data) {
      // 赋值后端返回的UserVO（包含userId、username等字段）
      currentUser.value = response.data;
      console.log("初始化用户状态成功：", currentUser.value);
    } else {
      // 后端返回异常（如Token无效、用户不存在）
      currentUser.value = {};
      ElMessage.warning(`获取用户信息失败：${response.message || '未知错误'}`);
      console.warn("初始化用户状态：后端返回异常", response);
    }

  } catch (error) {
    // 捕获网络错误、请求超时等异常
    currentUser.value = {};
    ElMessage.error("获取用户信息异常，请检查网络或重新登录");
    console.error("初始化用户状态异常：", error);
  }
};

// 获取歌单详情（参数为后端返回的playlistId）
const getPlaylistDetail = async (playlistId) => {
  if (!playlistId) return // 避免空ID请求
  detailLoading.value = true
  dialogVisible.value = true
  try {
    const res = await http.get(`/playlist/getPlaylistDetail/${playlistId}`)
    if (res.code === 0) {
      // 直接赋值后端返回的完整数据，确保likeStatus同步
      playlistDetail.value = {
        ...res.data,
        // 给歌曲/评论添加加载状态默认值（避免undefined）
        songs: res.data.songs?.map(song => ({ ...song, likeLoading: false })) || [],
        comments: res.data.comments?.map(comment => ({
          ...comment,
          likeLoading: false,
          deleteLoading: false,
          isLiked: comment.isLiked || false // 确保点赞状态有默认值
        })) || []
      }
      // 未登录时强制重置所有收藏状态为0
      if (!isLogin()) {
        playlistDetail.value.likeStatus = 0
        playlistDetail.value.songs = playlistDetail.value.songs.map(song => ({
          ...song,
          likeStatus: 0
        }))
        playlistDetail.value.comments = playlistDetail.value.comments.map(comment => ({
          ...comment,
          isLiked: false
        }))
      }
    } else {
      ElMessage.error(`获取歌单详情失败：${res.message}`)
    }
  } catch (error) {
    console.error('请求歌单详情接口异常:', error)
    ElMessage.error('网络异常，获取歌单详情失败')
  } finally {
    detailLoading.value = false
  }
}
// 歌单收藏/取消收藏（根据后端likeStatus切换）
const toggleLikeStatus = async () => {
  const { playlistId, likeStatus } = playlistDetail.value
  // 基础校验
  if (!isLogin()) {
    showLogin()
    return
  }
  if (!playlistId) {
    ElMessage.error('歌单ID异常，无法操作')
    return
  }

  toggleLikeLoading.value = true // 开启加载状态
  try {
    let res;
    if (likeStatus === 1) {
      // 取消收藏：请求后端取消接口
      res = await http.delete('/favorite/cancelCollectPlaylist', {
        params: { playlistId: playlistId }
      });
    } else {
      // 收藏：请求后端收藏接口
      res = await http.post('/favorite/collectPlaylist', null, {
        params: { playlistId: playlistId }
      });
    }

    // 结果处理：刷新详情页以同步最新likeStatus
    if (res.code === 0) {
      await getPlaylistDetail(playlistId);
      ElMessage.success(likeStatus === 1 ? '取消收藏成功' : '收藏成功');
      // 若当前在收藏标签页，同步刷新收藏列表
      if (activeTab.value === 'favorite') {
        fetchFavoritePlaylists();
      }
    } else {
      ElMessage.error(res.message || '操作失败');
    }
  } catch (error) {
    console.error('歌单收藏/取消异常:', error)
    ElMessage.error('网络异常，操作失败')
  } finally {
    toggleLikeLoading.value = false // 关闭加载状态
  }
};

// 歌曲收藏/取消收藏（根据song.likeStatus）
const likeSong = async (song) => {
  const { id, likeStatus } = song
  // 基础校验
  if (!isLogin()) {
    showLogin()
    return
  }
  if (!id) {
    ElMessage.error('歌曲ID异常，无法操作')
    return
  }

  song.likeLoading = true // 开启歌曲加载状态
  try {
    const res = likeStatus === 1
        ? await http.delete('/favorite/cancelCollectSong', {
          params: { songId: id }
        })
        : await http.post('/favorite/collectSong', null, {
          params: { songId: id }
        })

    // 结果处理：直接更新当前song的likeStatus
    if (res.code === 0) {
      song.likeStatus = likeStatus === 1 ? 0 : 1
      ElMessage.success(likeStatus === 1 ? '歌曲取消收藏成功' : '歌曲收藏成功')
    } else {
      ElMessage.error(res.message || '操作失败')
    }
  } catch (error) {
    console.error('歌曲收藏异常:', error)
    ElMessage.error('网络异常，操作失败')
  } finally {
    song.likeLoading = false // 关闭加载状态
  }
}

// 发表评论
const sendComment = async () => {
  const { playlistId } = playlistDetail.value
  // 基础校验
  if (!isLogin()) {
    showLogin()
    return
  }
  const content = commentContent.value.trim()
  if (!content) {
    ElMessage.warning('请输入评论内容')
    return
  }
  if (!playlistId) {
    ElMessage.error('歌单信息异常，无法发表评论')
    return
  }

  sendCommentLoading.value = true
  try {
    const res = await http.post('/comment/addPlaylistComment', {
      content: content,
      playlistId: playlistId,
      userId: currentUser.value.userId
    })
    if (res.code === 0) {
      ElMessage.success('评论发布成功！')
      await getPlaylistDetail(playlistId) // 刷新详情页显示新评论
      commentContent.value = '' // 清空输入框
    } else {
      ElMessage.error(`评论发布失败：${res.message}`)
    }
  } catch (error) {
    console.error('发表评论异常:', error)
    ElMessage.error('网络异常，发表评论失败')
  } finally {
    sendCommentLoading.value = false
  }
}

// 切换评论点赞状态（点赞/取消点赞）
const toggleCommentLike = async (comment) => {
  const { commentId, isLiked } = comment;
  if (!commentId) {
    ElMessage.error('评论ID异常，无法操作点赞');
    return;
  }

  comment.likeLoading = true; // 显示加载状态
  try {
    let res;
    if (isLiked) {
      // 取消点赞：调用 /comment/cancelLikeComment/{commentId}
      res = await http.patch(`/comment/cancelLikeComment/${commentId}`);
    } else {
      // 点赞：调用 /comment/likeComment/{commentId}
      res = await http.patch(`/comment/likeComment/${commentId}`);
    }

    if (res.code === 0) {
      // 同步更新前端显示的点赞数和状态
      comment.likeCount = isLiked
          ? (comment.likeCount || 0) - 1
          : (comment.likeCount || 0) + 1;
      comment.isLiked = !isLiked;
      ElMessage.success(isLiked ? '取消点赞成功' : '点赞成功');
    } else {
      ElMessage.error(res.message || '操作失败');
    }
  } catch (error) {
    console.error('评论点赞/取消异常:', error);
    ElMessage.error('网络异常，操作失败');
  } finally {
    comment.likeLoading = false; // 关闭加载状态
  }
};

// 删除评论
const deleteComment = async (comment) => {
  const { commentId, playlistId } = { ...comment, ...playlistDetail.value };
  if (!commentId || !playlistId) {
    ElMessage.error('评论/歌单ID异常，无法删除');
    return;
  }

  comment.deleteLoading = true; // 显示加载状态
  try {
    // 调用 /comment/deleteComment/{commentId}（无额外参数）
    const res = await http.delete(`/comment/deleteComment/${commentId}`);
    if (res.code === 0) {
      ElMessage.success('删除评论成功');
      await getPlaylistDetail(playlistId); // 刷新歌单详情，移除已删评论
    } else {
      ElMessage.error(res.message || '删除失败');
    }
  } catch (error) {
    console.error('删除评论异常:', error);
    ElMessage.error('网络异常，删除失败');
  } finally {
    comment.deleteLoading = false; // 关闭加载状态
  }
};
// 查看歌单详情页
const viewPlaylist = (pl) => {
  router.push(`/playlist/${pl.id || pl.playlistId}`) // 兼容两种ID字段
}
// 显示登录弹窗
const showLogin = () => {
  window.dispatchEvent(new CustomEvent('showLoginModal'))
}

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
}
// 监听登录状态变化（token变化时刷新用户状态）
watch(() => getToken(), (newVal) => {
  initUserState()
  // 若弹窗打开，刷新歌单详情的收藏状态
  if (newVal && dialogVisible.value) {
    getPlaylistDetail(playlistDetail.value.playlistId)
  }
})



/** 加载推荐歌单 */
// 修改 RecommendView.vue 中的 loadRecommendedPlaylists 函数
// -------------------------- 2. 推荐歌单相关 --------------------------
const loadRecommendedPlaylists = async () => {
  playlistLoading.value = true
  try {
    const res = await playlistApi.getRecommended()
    if (res.code === 0) { // 注意：若用了request.js拦截器，res已直接是后端的data（跳过外层）
      // 【关键】补充缺失的 songCount 和 playCount，避免显示异常
      const formattedPlaylists = res.data.map(playlist => ({
        ...playlist,
        songCount: playlist.songCount || 0, // 若无歌曲数，默认显示0首
        playCount: playlist.playCount || 0, // 若无播放量，默认显示0
        // 可选：若接口返回的coverUrl为空，补充默认封面
        coverUrl: playlist.coverUrl || `https://picsum.photos/120/120?random=${playlist.id}`
      }))
      recommendedPlaylists.value = formattedPlaylists
      ElMessage.success('推荐歌单加载成功')
    } else {
      recommendedPlaylists.value = []
      ElMessage.error(res.message || '获取推荐歌单失败')
    }
  } catch (err) {
    console.error('推荐歌单加载异常：', err)
    ElMessage.error('加载推荐歌单失败，请重试')
    recommendedPlaylists.value = []
  } finally {
    playlistLoading.value = false
  }
}

// -------------------------- 3. 推荐歌曲相关 --------------------------
/** @type {SongItem[]} 推荐歌曲列表 */
const recommendedSongs = ref([])
const songLoading = ref(false)
const { playSong: playSongInPlayer, setPlaylist } = usePlayer()

/** 加载推荐歌曲（对接 SongController） */
const loadRecommendedSongs = async () => {
  songLoading.value = true
  try {
    // 调用歌曲推荐接口（修正：直接使用res.code判断，因http拦截器已处理外层）
    const res = await songApi.getRecommendedSongs()

    // 修正：正确的响应判断逻辑（假设后端返回 {code:0, data: [], message:''}）
    if (res.code === 0) {
      const rawSongs = res.data || []
      // 映射后端 SongVo 到前端 SongItem 格式（修正：统一使用likeStatus字段）
      recommendedSongs.value = rawSongs.map(song => ({
        ...song,
        id: song.songId, // 统一唯一标识
        likeStatus: song.likeStatus || 0, // 明确收藏状态：0=未收藏，1=已收藏
        songName: song.songName || '未知歌曲',
        artistName: song.artistName || '未知歌手',
        album: song.album || '未知专辑',
        likeLoading: false // 新增加载状态字段
      }))
      ElMessage.success(`推荐歌曲加载成功，共${recommendedSongs.value.length}首`)
    } else {
      recommendedSongs.value = []
      ElMessage.error(res.message || '获取推荐歌曲失败')
    }
  } catch (err) {
    console.error('推荐歌曲加载异常：', err)
    ElMessage.error(err.message || '网络错误，无法加载推荐歌曲')
    recommendedSongs.value = []
  } finally {
    songLoading.value = false
  }
}

// 播放歌曲 - 修正：使用当前推荐列表作为播放源
const playSong = (song) => {
  // 查找当前歌曲在推荐列表中的索引
  const index = recommendedSongs.value.findIndex(item => item.id === song.id)
  if (index === -1) {
    ElMessage.warning('未找到该歌曲信息')
    return
  }

  // 修正：使用推荐歌曲列表作为播放列表
  setPlaylist(recommendedSongs.value, index)
  playSongInPlayer(song, recommendedSongs.value, index)
  ElMessage.success(`开始播放: ${song.songName} - ${song.artistName}`)
}



/** 跳转全部歌曲页（携带分页参数） */
const goToAllSongs = () => {
  router.push({
    path: '/library',
    query: { pageNum: 1, pageSize: 10 } // 初始分页参数
  })
}

// -------------------------- 4. 收藏相关 --------------------------
/** 歌曲收藏/取消收藏 */
const songLike = async (song) => {
  // 登录校验：未登录触发登录弹窗
  if (!isLogin()) {
    window.dispatchEvent(new CustomEvent('showLoginModal'))
    return
  }

  if (!song.songId) {
    ElMessage.warning('歌曲ID无效，无法操作')
    return
  }

  try {
    if (song.isLiked) {
      // 取消收藏
      await favoriteApi.cancelCollect(song.songId)
    } else {
      // 新增收藏
      await favoriteApi.collectSong(song.songId)
    }
    // 本地更新状态（无需重新请求列表）
    song.isLiked = !song.isLiked
    ElMessage.success(song.isLiked ? '收藏成功' : '取消收藏成功')
  } catch (err) {
    console.error('收藏操作异常：', err)
    ElMessage.error(err.response?.data?.message || '操作失败，请重试')
  }
}

// -------------------------- 页面初始化 --------------------------
onMounted(async () => {
  // 1. 优先读取缓存的轮播图（减少请求）
  const cachedBanners = sessionStorage.getItem('validBanners')
  if (cachedBanners) {
    bannerList.value = JSON.parse(cachedBanners)
  } else {
    await loadBanner()
  }

  // 2. 并行加载歌单和歌曲（提升首屏速度）
  await Promise.all([
    loadRecommendedPlaylists(),
    loadRecommendedSongs()
  ])
})
</script>

<style scoped>
/* 页面容器样式 */
.recommend-view {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

/* 轮播图样式（适配 ElImage） */
.banner-img {
  width: 100%;
  height: 200px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 推荐区块通用样式 */
.recommend-section {
  margin-top: 30px;
}

/* 区块标题栏样式 */
.section-header, .section-header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.section-header h3, .section-header-actions h3 {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

/* 歌单卡片列表样式 */
.card-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-top: 10px;
}

.recommend-card {
  width: 140px;
  cursor: pointer;
  transition: all 0.2s ease;
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  border-radius: 8px;
}

.recommend-card:disabled {
  cursor: not-allowed;
  opacity: 0.7;
}

.recommend-card:hover:not(:disabled) {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
}

/* 歌单封面样式 */
.card-cover {
  width: 120px;
  height: 120px;
  margin: 0 auto 10px;
  border-radius: 4px;
}

/* 歌单标题样式（溢出省略） */
.card-label {
  font-size: 14px;
  line-height: 1.5;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  padding: 0 8px;
  color: #333;
}

/* 歌单元信息样式（歌曲数、播放量） */
.card-meta {
  font-size: 12px;
  color: #999;
  display: flex;
  justify-content: space-between;
  padding: 0 8px;
  margin-top: 5px;
}

/* 歌曲标题区样式（封面+名称） */
.song-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 歌曲小封面样式 */
.song-cover-sm {
  width: 30px;
  height: 30px;
  border-radius: 2px;
}





.el-table .el-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 空状态提示样式 */
.empty-tip {
  width: 100%;
  text-align: center;
  color: #999;
  padding: 40px 0;
  font-size: 14px;
}

/* 歌单骨架屏样式 */
.playlist-skeleton {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.playlist-skeleton .el-skeleton,
.el-skeleton--text {
  border-radius: 8px;
}



.playlist-view {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 60px);
}

/* 顶部操作区样式 */
.top-actions {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}

/* 加载状态样式 */
.loading {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-top: 20px;
}

.skeleton-item {
  width: calc((100% - 5 * 20px) / 6);
  height: 280px;
  border-radius: 8px;
}

/* 无数据提示 */
.no-data {
  text-align: center;
  padding: 50px 0;
}

/* 歌单网格布局 */
.playlist-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-top: 20px;
}

/* 歌单卡片样式 */
.playlist-card {
  width: calc((100% - 5 * 20px) / 6);
  cursor: pointer;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.playlist-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.playlist-cover {
  width: 100%;
  height: 160px;
  object-fit: cover;
  border-radius: 4px;
  margin-bottom: 10px;
  cursor: pointer;
}

.playlist-info {
  line-height: 1.4;
  padding: 0 5px;
}

.playlist-name {
  font-weight: 500;
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-bottom: 4px;
}

.playlist-desc {
  font-size: 12px;
  color: #909399;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 登录提示样式 */
.need-login-tip {
  text-align: center;
  padding: 50px 0;
}

.need-login-comment {
  margin-top: 10px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

/* 详情弹窗样式 */
.detail-header {
  display: flex;
  align-items: flex-start;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.detail-cover {
  width: 200px;
  height: 200px;
  object-fit: cover;
  margin-right: 20px;
  border-radius: 8px;
}

.detail-info {
  flex: 1;
  min-width: 300px;
}

.detail-info h3 {
  margin-bottom: 15px;
  font-size: 24px;
}

.detail-info p {
  margin-bottom: 10px;
  line-height: 1.6;
}

.detail-actions {
  margin-top: 20px;
}

/* 歌曲列表样式 */
.detail-songs, .detail-comments {
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.detail-songs h4, .detail-comments h4 {
  margin-bottom: 15px;
  font-size: 18px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.song-cover {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
}

/* 未登录状态下的歌曲收藏按钮样式 */
.login-prompt-btn {
  color: #606266;
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  display: inline-flex;
  align-items: center;
}

.login-prompt-btn:hover {
  background-color: #e9ecef;
  border-color: #dcdfe6;
}

.icon-heart {
  display: inline-block;
  width: 14px;
  height: 14px;
  margin-right: 4px;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='14' height='14' viewBox='0 0 24 24' fill='none' stroke='%23606266' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z'/%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-size: contain;
}

/* 评论区样式 */
.comments-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-top: 15px;
}

.comment-card {
  transition: box-shadow 0.3s ease;
}

.comment-card:hover {
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
}

.comment-item {
  display: flex;
  align-items: flex-start;
}

.comment-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  margin-right: 10px;
}

.comment-info {
  flex: 1;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.comment-username {
  font-weight: bold;
  font-size: 14px;
}

.comment-time {
  font-size: 12px;
  color: #909399;
}

.comment-content {
  margin-bottom: 8px;
  line-height: 1.6;
}

.comment-actions {
  display: flex;
  gap: 10px;
}

.no-comment {
  text-align: center;
  padding: 40px 20px;
  color: #909399;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.add-comment {
  margin-top: 20px;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .playlist-card {
    width: calc((100% - 4 * 20px) / 5);
  }
}

@media (max-width: 992px) {
  .playlist-card {
    width: calc((100% - 3 * 20px) / 4);
  }

  .detail-cover {
    width: 150px;
    height: 150px;
  }
}

@media (max-width: 768px) {
  .playlist-card {
    width: calc((100% - 2 * 20px) / 3);
  }

  .search-input {
    width: 100%;
  }

  .detail-header {
    flex-direction: column;
  }

  .detail-cover {
    margin-bottom: 15px;
    margin-right: 0;
    width: 100%;
    max-width: 300px;
  }

  /* 适配移动端表格按钮 */
  .login-prompt-btn {
    padding: 5px 8px;
    font-size: 12px;
  }
}

@media (max-width: 576px) {
  .playlist-card {
    width: calc((100% - 1 * 20px) / 2);
  }

  .skeleton-item {
    width: calc((100% - 1 * 20px) / 2);
  }

  .detail-info {
    min-width: auto;
  }

  .detail-info h3 {
    font-size: 20px;
  }

  /* 移动端优化按钮显示 */
  .login-prompt-btn {
    padding: 4px 6px;
    font-size: 11px;
  }
}
</style>